#####################################################################
# Product:      KnowledgeEngine (Plone Edition)
#
# File:         BackButton.py
#
# Copyright:    Copyright (c) 2004, Faulkner Technologies
#
# Author:       Brian Oliver
#
# Description:  This file defines the BackButton class, a simple
#               Button for placement in Toolbars
#
# See Also:     Element, Toolbar
#####################################################################

#####################################################################
## Knowledge Engine Library Imports
from Products.KnowledgeEngine.Common import *
from Products.KnowledgeEngine.Core import *
from Products.KnowledgeEngine.Elements.Toolbar.ToolbarTool import ToolbarTool, ToolbarToolInfo
from Products.KnowledgeEngine.PropertyDefinition import *
from Products.KnowledgeEngine.PropertyTypes import *
from Products.KnowledgeEngine.PropertyFormats import *
from Products.KnowledgeEngine.PropertyStructures import *

#####################################################################
## Zope Library Imports
from Globals import DTMLFile
from App.ImageFile import ImageFile

#####################################################################
## Python Library Imports
# (none)

#####################################################################
## Constants

#display mode constants
dm_ALL_PAGES = "ALL_PAGES"
dm_NOT_ON_FIRST_PAGE = "NOT_ON_FIRST_PAGE"

#the display mode for the button
dm_VALUES = [("All Pages (and wrap first to last)",dm_ALL_PAGES), ("All Pages but the First (no wrapping)",dm_NOT_ON_FIRST_PAGE)]

#####################################################################
## BackButtonInfo Class Definition
class BackButtonInfo(ToolbarToolInfo):
    """
        Defines the class info methods, defining information about
        the class without needing an instance of the class
    """
    
    #---------------------------------------------------------------#
    
    def getClassName(self):
        """
            Returns the name of the class for which 
            we are providing information.
        """
        return "BackButton"

    #---------------------------------------------------------------#

    def getDisplayName(self):
        """
            Return a friendly name for the class instances
            (this is used for displaying in lists etc)
        """
    
        return "Back Button"
        
    #---------------------------------------------------------------#

    def getIdentityType(self):
        """
            Return the identity type.  
        """
        
        return "toolBack"
        
    #---------------------------------------------------------------#
    
    def getClassIcon(self):
        """
            Return the appropriate icon file for the class.
        """
        
        return ImageFile('skins/BackButton_icon.png', globals())
        
    #---------------------------------------------------------------#

    def isPermittedInContainer(self, containerClassInfo, containerInstance = None, instance=None):
        """
            ABSTRACT: Returns if class instances (instance) is permitted in 
            the specified container (containerInstance)
            
            NOTE: This is from this class' instance perspective.
        """
        
        #DEFAULT RULE: BackButtons are only permitted in Toolbars
        return containerClassInfo.isInstanceOf('Toolbar') and ((containerInstance == None) or (containerInstance != None and len(containerInstance.getChildrenByInstanceOf(self.getClassName())) == 0))
    
    #---------------------------------------------------------------#

    def onConfigureProperties(self):
        """
            Automatically called by the Knowledge Engine once
            the class has been loaded.  Use this method to register 
            class specific properties using the PropertyReflection interface.
            
            If this class is sub-classed, a call must be made to
            the super-class to ensure super-class properties are
            correctly registered
            
            NOTE: This method is called before ClassInfo.onAfterStartup()            
        """

        #initialise the super-class properties for reflection
        ToolbarToolInfo.onConfigureProperties(self)

        #set the default title
        self.getPropertyDefinition('title').setDefaultValue('< Back')

        #set the default id
        self.getPropertyDefinition('id').setDefaultValue('btnBack')
        
        #add the 'displayMode' property        
        self.addPropertyDefinition(PropertyDefinition(identity="displayMode", displayName="Display On...", description="Criteria to display the button during an assessment", defaultValue=dm_ALL_PAGES, propertyType=pt_STRING, propertyFormat=pf_NATIVE, propertyStructure=ps_ATOMIC, hasEnumeratedValues=true, enumeratedValuesMapping=dm_VALUES))        

    #---------------------------------------------------------------#

#####################################################################
## BackButton Class Definition
class BackButton(ToolbarTool):
    """
        A class to represent a button in a toolbar
    """

    #---------------------------------------------------------------#

    #ABSTRACT TRANSIENT: a ClassInfo implementation instance to provide info about this class
    _CLASSINFO = BackButtonInfo()

    #---------------------------------------------------------------#

    # Custom zope manage_preview to permit previews of components.
    preview_html = DTMLFile('index_html', globals())

    #---------------------------------------------------------------#

    def __init__(self, id, identity):
        "Constructor for the BackButton"        

        ToolbarTool.__init__(self, id, identity)
        
        #perform onAfterInstanciation processing
        self.onAfterInstanciation()

    #---------------------------------------------------------------#

    def onAfterInstanciation(self):
        """
            Handle Knowledge Engine specific actions after this object 
            has been loaded into memory.  
            
            This is useful for performing backwards compatibility
        """        
        
        #perform default processing
        ToolbarTool.onAfterInstanciation(self)
        
    #---------------------------------------------------------------#

    def isPreviewPermitted(self):
        """
            Return if the Element is allowed to be previewed.
            
            By default all elements can't be previewed, some however
            should can be previewed. eg: HTMLHeaderFooters
        """
        
        return true
        
    #---------------------------------------------------------------#

    def getDisplayMode(self):
        """
            Return the display mode for the component
        """
        
        if not hasattr(self, "displayMode"):
            return dm_ALL_PAGES
        else:
            return self.displayMode
        
    #---------------------------------------------------------------#

    def getContent(self, contentZone, forGenericObject = None, assessment = None):
        """
            Return the Element generated 
            content for the specified contentZone (a string).   

            This method is called by the Model.index_html dtml file
            to customise the appearance of the output.
            
            By overriding this method, Elements have the opportunity
            to perform customization of the output from a Model
            during the assessment process.
        """
        
        #the result
        result = ""

        if contentZone == "PAGE_REFRESH":
            if self.getDisplayMode() == dm_NOT_ON_FIRST_PAGE:
                result += "Try.these(function() { $('btnTopBack', 'btnBottomBack').invoke(isFirstPage() ? 'hide' : 'show') });\n"

        if contentZone == "TOOLBAR_TOP" or contentZone == "TOOLBAR_BOTTOM":
        
            #output the button
            if contentZone == "TOOLBAR_TOP":
                prefix = "Top"
            else:
                prefix = "Bottom"
            
            #is the button displayed all the time?
            if self.getDisplayMode() == dm_NOT_ON_FIRST_PAGE:    
                displayMode = "none"
            else:
                displayMode = "inline"

            #determine the button content
            result += '<input type="button" id="btn%sBack" class="keButton" style="display:%s" value="%s" onClick="navigateToPage(getPreviousPage());">' % (prefix, displayMode, self.getTitle())

            #get the page we are currently in (the forGenericObject)            
            lPage = forGenericObject
                                   
            #(if we have been supplied a context section)
            if lPage != None:
                
                #get the model for the page                
                lModel = lPage.getModel()
                
                #does the model have more than one page?                
                if len(lModel.getPages(assessment)) <= 1:
                    #no button for less than 2 pages
                    result = ""                              
                   
        return result
        
    #---------------------------------------------------------------#

#####################################################################
## Class Initialisation

# Register Class Information with the Knowledge Engine
registerGenericObjectClass(BackButton)

#####################################################################
